import * as api from './api';
import {PAGE_CODE} from './constants';
import {PAGE_TEN} from '../constants';
import {
    getCurrentUserPagePermissionsSuccess,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsApi
} from 'Shared/actions/currentUserContext';
export const ERROR_CODE = 'error';
export const GET_INIT_DATA_BEGIN = 'GET_INIT_DATA_BEGIN';
export const GET_INIT_DATA_SUCCESS = 'GET_INIT_DATA_SUCCESS';
export const GET_INIT_DATA_FAIL = 'GET_INIT_DATA_FAIL';
import {conventTableCondition} from '../utils';
import moment from 'moment';

const getInitDataBegin = () => ({
    type: GET_INIT_DATA_BEGIN
});

const getInitDataSuccess = data => ({
    type: GET_INIT_DATA_SUCCESS,
    data
});
const getInitDataFail = () => ({
    type: GET_INIT_DATA_FAIL
});
/**初始化 */
/*==============================查询列表================================= */
export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
const getListSuccess = (condition, data) => ({
    type: GET_LIST_SUCCESS,
    condition,
    data
});
export const getListFail = () => ({
    type: GET_LIST_FAIL
});
/*==============================初始化API================================= */
//获取初始化数据和权限
export const getInitData = () => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.getInitData().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(PAGE_CODE).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });

    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};

/*==============================查询action================================= */
const conventDate = (condition = {}) => {
    const {createTime, ...others} = condition;
    if(!createTime || createTime.length === 0) return condition;
    return {
        ...others,
        beginCreateTime: moment(createTime[0]).toISOString(),
        endCreateTime: moment(createTime[1]).toISOString(),
    };
};
//获取查询列表
export const getList = condition => dispatch => {
    dispatch(getListBegin());
    const queryCondition = conventDate(conventTableCondition(condition));
    return api.getList(queryCondition).then(res => {
        if(res.ok)
            dispatch(getListSuccess(condition, res.data));
        else
            dispatch(getListFail());
    });
};

//修改查询条件
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//重置查询条件
export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});

//按钮搜索
export const querySearch = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    const pageTableCondition = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    condition.pageSize = pageTableCondition.pageSize || PAGE_TEN.size;
    condition.sortedColumnKey = pageTableCondition.sortedColumnKey;
    condition.sortedOrder = pageTableCondition.sortedOrder;
    dispatch(getList(condition));
};
//分页排序搜索
export const tableSearch = page => (dispatch, getState) => {
    const query = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    if(!query.pageIndex || !page)
        query.pageIndex = 0;
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

//选择查询条件
export const SAVE_QUERY_DEALER = 'SAVE_QUERY_DEALER';
export const saveQueryDealer = data => ({
    type: SAVE_QUERY_DEALER,
    data
});

/*==============================新增修改action================================= */
export const onSubmit = (data, details) => () => {
    const addCondition = {
        brandId: data.brandId,
        dealerId: data.dealerId,
        customerOrderCode: data.customerOrderCode,
        partOrderTypeId: data.partOrderTypeId,
        paymentType: data.paymentType,
        partOrderPriceTerms: data.partOrderPriceTerms,
        account: data.account,
        carier: data.carier,
        receivedCompany: data.receivedCompany,
        receivedTelephone: data.receivedTelephone,
        receivedPerson: data.receivedPerson,
        receivedPersonPhone: data.receivedPersonPhone,
        receivedAddress: data.receivedAddress,
        receivedPort: data.receivedPort,
        shipmentPort: data.shipmentPort,
        transportType: data.transportType,
        remark: data.remark,
        details: details.map(v => ({
            partId: v.partId,
            planQuantity: v.planQuantity,
            oldPartId: v.oldPartId
        }))
    };
    const updateCondition = {
        brandId: data.brandId,
        customerOrderCode: data.customerOrderCode,
        partOrderTypeId: data.partOrderTypeId,
        paymentType: data.paymentType,
        partOrderPriceTerms: data.partOrderPriceTerms,
        account: data.account,
        carier: data.carier,
        receivedCompany: data.receivedCompany,
        receivedTelephone: data.receivedTelephone,
        receivedPerson: data.receivedPerson,
        receivedPersonPhone: data.receivedPersonPhone,
        receivedAddress: data.receivedAddress,
        receivedPort: data.receivedPort,
        shipmentPort: data.shipmentPort,
        transportType: data.transportType,
        remark: data.remark,
        rowVersion: data.rowVersion,
        details: details.map(v => ({
            partId: v.partId,
            planQuantity: v.planQuantity,
            oldPartId: v.oldPartId
        }))
    };
    return data.id ? api.modifyOrder(data.id, updateCondition)
        .then(res => ({success: res.ok})) : api.newOrder(addCondition).then(res => ({success: res.ok}));
};
/*==============================审核action================================= */
export const onApprove = (data, details) => () => {
    const condition = {
        approvedContent: data.approvedContent,
        remark: data.remark,
        rowVersion: data.rowVersion,
        details: details.map(v => ({
            partId: v.partId,
            oldPartId: v.oldPartId,
            approvedQuantity: v.approvedQuantity
        }))
    };
    return api.approveData(data.id, condition).then(res => ({success: res.ok}));
};
export const onReject = (data, details) => () => {
    const condition = {
        approvedContent: data.approvedContent,
        remark: data.remark,
        rowVersion: data.rowVersion,
        details: details.map(v => ({
            partId: v.partId,
            oldPartId: v.oldPartId,
            approvedQuantity: v.approvedQuantity
        }))
    };
    return api.rejectData(data.id, condition).then(res => ({success: res.ok}));
};

/*==============================点击导出清单action================================= */
export const detailExport = details => () => {
    const tmp = details.filter(d => d.isType === true || d.isTransport === true || d.partReplacementCode !== null);
    const addCondition = tmp.map(v => ({
        partId: v.partId,
        isType: v.isType,
        isTransport: v.isTransport,
        partReplacementCode: v.partReplacementCode,
    }));
    return api.detailExport(addCondition);
};

/*==============================导入模板action================================= */
export const partOrderPartImportTemp = () => () => api.partOrderPartImportTemp();

/**查询历史 */
/*==============================查询列表================================= */
export const GET_LIST_BEGIN_HIS = 'GET_LIST_BEGIN_HIS';
export const GET_LIST_SUCCESS_HIS = 'GET_LIST_SUCCESS_HIS';
export const GET_LIST_FAIL_HIS = 'GET_LIST_FAIL_HIS';
export const getListBeginHis = () => ({
    type: GET_LIST_BEGIN_HIS
});
const getListSuccessHis = (condition, data) => ({
    type: GET_LIST_SUCCESS_HIS,
    condition,
    data
});
export const getListFailHis = () => ({
    type: GET_LIST_FAIL_HIS
});
/*==============================查询action================================= */
const conventDateHis = (condition = {}) => {
    const {submitDate, ...others} = condition;
    if(!submitDate || submitDate.length === 0) return condition;
    return {
        ...others,
        beginSubmitDate: moment(submitDate[0]).toISOString(),
        endSubmitDate: moment(submitDate[1]).toISOString(),
    };
};
const conventStockDateHis = (condition = {}) => {
    const {stockCreatDate, ...others} = condition;
    if(!stockCreatDate || stockCreatDate.length === 0) return condition;
    return {
        ...others,
        beginStockCreatDate: moment(stockCreatDate[0]).toISOString(),
        endStockCreatDate: moment(stockCreatDate[1]).toISOString(),
    };
};
//获取查询列表
export const getListHis = condition => dispatch => {
    dispatch(getListBeginHis());
    const queryCondition = conventStockDateHis(conventDateHis(conventTableCondition(condition)));
    return api.getListHis(queryCondition).then(res => {
        if(res.ok)
            dispatch(getListSuccessHis(condition, res.data));
        else
            dispatch(getListFailHis());
    });
};

//修改查询条件
export const SAVE_QUERY_CONDITION_HIS = 'SAVE_QUERY_CONDITION_HIS';
export const saveQueryConditionHis = (name, value) => ({
    type: SAVE_QUERY_CONDITION_HIS,
    name,
    value
});
//重置查询条件
export const RESET_QUERY_PANEL_HIS = 'RESET_QUERY_PANEL_HIS';
export const resetQueryPanelHis = () => ({
    type: RESET_QUERY_PANEL_HIS,
});

//按钮搜索
export const querySearchHis = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryConditionHis']).toJS();
    const pageTableCondition = getState().getIn(['page', 'appState', 'queryBySortHis']).toJS();
    condition.pageSize = pageTableCondition.pageSize || PAGE_TEN.size;
    condition.sortedColumnKey = pageTableCondition.sortedColumnKey;
    condition.sortedOrder = pageTableCondition.sortedOrder;
    dispatch(getListHis(condition));
};
//分页排序搜索
export const tableSearchHis = page => (dispatch, getState) => {
    const query = getState().getIn(['page', 'appState', 'queryBySortHis']).toJS();
    if(!query.pageIndex || !page)
        query.pageIndex = 0;
    const condition = Object.assign({}, query, page);
    dispatch(getListHis(condition));
};
//选择查询条件
export const SAVE_QUERY_DEALER_HIS = 'SAVE_QUERY_DEALER_HIS';
export const saveQueryDealerHis = data => ({
    type: SAVE_QUERY_DEALER_HIS,
    data
});
/*==============================点击导出审核清单action================================= */
export const detailExportApprove = id => () => api.exportDetails(id);
